import { CONF } from "../configure/Assets.js";
import Type from "../experience/db/Type.js";
import {$$, _toast, app} from "../experience/utils/F7.js";

import Db from "../experience/db/Db.js";
import Net from "../experience/api/net.js";
import Api from "../experience/api/Api.js";
import Utils from "../experience/utils/Utils.js";
import Algorithm from "../experience/utils/Algorithm.js";
import Drawer from "../experience/drawer/Drawer.js";
import Emitter from "../experience/utils/Emitter.js";
import Uploader from "../component/other/Uploader.js";


const Style = ol.style.Style
const Point = ol.geom.Point;
const Text = ol.style.Text;
const Fill = ol.style.Fill;
const Feature = ol.Feature;
const Draw = ol.interaction.Draw;

class KJ29A {
    constructor() {
        if (KJ29A.instance) {
            return KJ29A.instance;
        }
        KJ29A.instance = this;

        this.toast = _toast;
        this.db = new Db();
        this.net = new Net();
        this.api = new Api();
        this.utils = new Utils();
        this.algo = new Algorithm();
        this.drawer = new Drawer();
        this.emitter = new Emitter();

        // 传感器类型图标
        this.sensor_types =  {
            1: '\ue624',
            2: '\ue628',
            3: '\ue62d',
            4: '\ue62a',
            5: '\ue626',
        };

        this.url = "http://192.168.180.251:8089/jeecg-boot/dp/sensor";

        // 配置需要使用theme
        this.utils.setLocalStorage("theme", true);
        $$(".ol-viewport").css("background", CONF.BACKGROUND);

        // 全局初始化
        this.init().then(async () => {
            this.header();
            this.controls();

            new Uploader();
            await this.refresh();
            console.log("Walküre Fly...");
        });
    }

    header() {
        const div1 = `
            <div id="vp-header">
                <button class="button button-fill color-primary" id="upload-popup">更新图纸</button>
                <button class="button button-fill color-primary" id="sensor-items">传感器列表</button>
            </div>
        `;
        $$("#article").append(div1);

        const div2 = `
            <div class="page" id="pannel" style="top: 60px; width: 20vw; height: 90vh;">
                <div class="page-title">
                    <span id="vl-title">选择传感器</span>
                    <div>
                        <i class="iconfont" style="font-size: 22px; cursor: pointer;" 
                            id="pannel-close">
                            &#xe6ba;
                        </i>
                    </div>
                </div>
                <div class="page-content"></div>
            </div>
        `;
        $$("#article").append(div2);
        $$("#pannel").hide();
    }

    async update(meta) {
        const meta_id = meta.meta_id;
        app.dialog.preloader("正在获取矿图...");
        const data = await this.api.getVector(meta_id);
        if (data.code === 0) {
            this.drawer.init(data.data.meta, data.data.layers);
            this.db.init(data.data).then(() => {
                this.drawer.location().then(() => {
                    this.refresh().then(() => {
                        app.dialog.close();
                    });
                });
            });
        }
    }

    async init() {
        const config = this.algo.getConfig();
        if (config === null) {
            const metas = await this.api.getMetas(CONF.MINE_CODE);
            if (metas.code === 0 && metas.data.length > 0) {
                await this.update(metas.data[0]);
            }
        } else {
            await this.drawer.location();
            await this.refresh();
        }
    }

    async message() {
        window.onload = function (e) {
            const json = { from: "valkyrja", load: 'true', type: "onload" };
            window.parent.postMessage(JSON.stringify(json), "*");
        }

        window.onmessage = async (e) => {
            const data = JSON.parse(e.data);
            if (data.from !== "valkyrja") return;

            if (data.type === "") {
                await self.createSensor(data, e);
            }
        }
    }

    async _api_sensor_list() {
        const url = this.url + "/list";
        return await this.net.post(url);
    }

    async _api_sensor_update(id, x, y, z) {
        const url = this.url + `/updateLoc`;
        return await this.net.post(url, {
            "id": id,
            "xloc": x,
            "yloc": y,
            "zloc": z
        });
    }

    async refresh() {
        const data = await this._api_sensor_list();
        if (data.code !== 200) {
            this.toast(data.message);
            return;
        }

        this.drawer.source(Type.Sensor).clear();
        for (let address of Object.values(data.result)) {
            for (let sensor of address) {
                if (sensor.xloc === null && sensor.yloc === null) {
                    continue;
                }

                const x = this.algo.normalX(sensor.xloc);
                const y = this.algo.normalY(sensor.yloc);

                const feature = new Feature();
                feature.setId(sensor.id);
                feature.set('type', Type.Sensor);
                const text = new Text({
                    text: this.sensor_types[sensor.sensortype],
                    fill: new Fill({ color: "green" }),
                    font: `normal 25px "iconfont"`
                });
                feature.setStyle(new Style({ text: text }));
                feature.setGeometry(new Point([x, y]));
                this.drawer.source(Type.Sensor).addFeature(feature);
            }
        }
    }

    start() {
        this.source = this.drawer.source(Type.Modify);
        this.draw = new Draw({ source: this.source, type: 'Point' });
        this.drawer.addInteraction(this.draw);
    }

    cancel() {
        this.drawer.removeInteraction(this.draw);
        this.drawer.source(Type.Modify).clear();
    }

    controls() {
        $$("#sensor-items").on("click", async () => {
            // 获取传感器数据
            const data = await this._api_sensor_list();
            if (data.code !== 200) {
                this.toast(data.message);
                return;
            }
            this.toast("点击列表选择传感器,将传感器移动到地图上。");

            $$("#pannel").show();
            $$("#pannel .page-content").empty();
            $$("#pannel .page-content").append(`
                <div class="block">
                    <div class="list simple-list">
                        <ul></ul>
                    </div>
                </div>
            `);

            for (let address of Object.values(data.result)) {
                for (let sensor of address) {
                    const id = `sensor-${sensor.id}`;
                    const li = `<li id=${id}><span>${sensor.id}</span></li>`;
                    $$("#pannel ul").append(li);
                    $$(`#${id}`).on("click", () => {
                        const sid = parseInt(id.split("-")[1]);
                        this.toast(`请将编号为 ${sid} 的传感器放置到轨迹线上。`);
                        this.start();
                        this.draw.on('drawend', async (event) => {
                            const point = event.feature.getGeometry().getCoordinates();
                            const x = this.algo.denormalX(point[0]);
                            const y = this.algo.denormalY(point[1]);
                            const data1 = await this._api_sensor_update(sid, x, y, 0);
                            if (data1.code !== 200) {
                                this.toast(data1.message);
                                this.cancel();
                                return;
                            }

                            const data2 = await this._api_sensor_list();
                            if (data2.code !== 200) {
                                this.toast(data2.message);
                                return;
                            }

                            await this.refresh();
                            this.cancel();
                        });
                    });
                }
            }
        });

        $$("#pannel-close").on("click", () => {
            $$("#pannel").hide();
        });
    }
}

new KJ29A();